package com.ifast.demo.job;

import com.alibaba.fastjson.JSON;
import com.ifast.asset.domain.TaskrecordDO;
import com.ifast.asset.service.TaskrecordService;
import com.ifast.asset.util.NmapExecuteUtil;
import com.ifast.demo.controller.FindSubDomain;
import com.ifast.demo.domain.DomainDO;
import com.ifast.demo.service.DomainService;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class FindSubJob implements Runnable{

    String domain;
    Integer level;
    List<String> domains;
    NmapExecuteUtil nmapExecuteUtil;
    DomainService domainService;
    TaskrecordService taskrecordService;
    Integer type;

    public FindSubJob (String domain , Integer level,Integer type, NmapExecuteUtil nmapExecuteUtil, DomainService domainService, TaskrecordService taskrecordService){

        this.domain=domain;
        this.level=level;
        this.nmapExecuteUtil=nmapExecuteUtil;
        this.domainService = domainService;
        this.taskrecordService =taskrecordService;
        this.type=type;
    }
    @Override
    public void run() {

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        DomainDO domainDO = new DomainDO();
        domainDO.setDomain(domain);
        domainDO.setLevel(level);
        domainDO.setTime(simpleDateFormat.format(new Date()));
        domainService.insert(domainDO);
        FindSubDomain findSubDomain = new FindSubDomain();
        if(type==1){
            findSubDomain.setDomain(domain);
            findSubDomain.readDict();

            try{
                findSubDomain.FindbySheet();
            }catch (Exception e){
                e.printStackTrace();
            }
        }else {
            //调用爆破函数
            findSubDomain.setDomain(domain);
            try {
                findSubDomain.startEnumSub(level);
            }catch (Exception e){
                e.printStackTrace();
            }
        }


        List<Map<String,Object>> lists = findSubDomain.getDomains();
        //将扫描记录保存到mysql中
        String json = JSON.toJSONString(lists);
        domainDO.setResult(json);
        domainService.updateById(domainDO);

        TaskrecordDO record = new TaskrecordDO();
        record.setIp(domain);
        record.setTaskName("域名爆破："+domain);
        record.setType("0");
        record.setTime(simpleDateFormat.format(new Date()));
        record.setCron("");
        record.setDomainid(domainDO.getId());
        taskrecordService.insert(record);
        for (int i = 0 ; i < lists.size() ; i++){

            TaskrecordDO re = new TaskrecordDO();
            re.setId(record.getId());
            re.setTaskName("域名爆破："+domain);
            re.setType("0");
            re.setTime(simpleDateFormat.format(new Date()));
            re.setCron("");
            re.setDomainid(domainDO.getId());
            re.setIp(lists.get(i).get("domain").toString());
            nmapExecuteUtil.execute(re);
        }
    }
}
